package com.kgc.itrip.controller;

import com.kgc.itrip.common.Constants;
import com.kgc.itrip.common.DtoUtil;
import com.kgc.itrip.common.EmptyUtils;
import com.kgc.itrip.common.MD5;
import com.kgc.itrip.component.RedisTools;
import com.kgc.itrip.dto.Dto;
import com.kgc.itrip.pojo.ItripUser;
import com.kgc.itrip.response.ResultCode;
import com.kgc.itrip.service.ItripUserService;
import com.kgc.itrip.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录的控制器
 *
 * @author lrg on 2021/3/16
 * @since 1.0.0
 */
@Api(value = "登录的控制器")
@RestController
@RequestMapping("/api")
public class LoginController {

    @Resource
    private ItripUserService userService;
    @Resource
    private TokenService tokenService;
    @Resource
    private RedisTools redisTools;

    @ApiOperation(value = "根据用户名、密码进行统一认证",
            httpMethod = "POST",notes = "根据用户名、密码进行统一认证",
            protocols = "http",produces = "application/json;charset=UTF-8",
            consumes = "application/json")
    @PostMapping(value="/dologin")
    public Dto doLogin(@RequestParam String name,
                       @RequestParam String password,
                       HttpServletRequest request) throws Exception {
        if(EmptyUtils.isEmpty(name)){
            return DtoUtil.returnFail(ResultCode.LOGIN_USERCODE_IS_NULL.getMsg(),
                    ResultCode.LOGIN_USERCODE_IS_NULL.getCode());
        }
        if(EmptyUtils.isEmpty(password)){
            return DtoUtil.returnFail(ResultCode.PASSWORD_IS_NULL.getMsg(),
                    ResultCode.PASSWORD_IS_NULL.getCode());
        }
        //调用业务员逻辑层判断用户名和密码是否正确
        Map<String,Object> params = new HashMap<>();
        params.put("userCode",name);
        params.put("activated", Constants.USER_STATUS.ACTIVED);
        params.put("userPassword", MD5.getMd5(password,32));
        List<ItripUser> userList = userService.getItripUserListByMap(params);
        ItripUser itripUser = null;
        if(userList!=null && userList.size()==1){
            itripUser = userList.get(0);
        }
        if(itripUser==null){
            return DtoUtil.returnFail(ResultCode.LOGIN_ERROR.getMsg(),ResultCode.LOGIN_ERROR.getCode());
        }
        //如果代码能走到这里说明查询到数据
        Map<String,String> tokenInfo = new HashMap<>();
        //1.获取token
        String agent = request.getHeader("User-Agent");
        String token = tokenService.generateToken(agent, itripUser);
        tokenInfo.put("token",token);
        tokenInfo.put("ticket","");
        String[] tokenDetails = token.split("-");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date TokenGenTime = formatter.parse(tokenDetails[3]);//获取token生成时间
        tokenInfo.put("genTime",String.valueOf(TokenGenTime.getTime()));
        tokenInfo.put("expTime",String.valueOf(TokenGenTime.getTime()+Constants.SESSION_TIMEOUT * 1000));
        //将用户的信息保存到redis中
        itripUser.setUserPassword(null);
        tokenService.save(token,itripUser);
        return DtoUtil.returnSuccess("登录成功",tokenInfo);
    }


    @ApiOperation(value = "用户注销",
            httpMethod = "GET",notes = "用户注销",
            protocols = "http",produces = "application/json;charset=UTF-8",
            consumes = "application/json")
    @GetMapping(value="/logout")
    public Dto logOut(HttpServletRequest request) throws Exception {
        String userAgent = request.getHeader("User-Agent");
        String token = request.getHeader("token");
        return userService.logOut(userAgent,token);
    }
}
